package com.gin.common.util;

import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 * create  on 2019-12-30 18:04
 */
public class GsonUtil {

    private static Gson gson = new Gson();

    private GsonUtil() {
    }

    /**
     * 转成json
     *
     * @param object
     * @return
     */
    public static String gsonString(Object object) {
        String gsonString = null;
        if (gson != null) {
            gsonString = gson.toJson(object);
        }
        return gsonString;
    }

    /**
     * 转成bean
     *
     * @param jsonStr json 字符串
     * @param cls     类型
     * @return
     */
    public static <T> T gsonToBean(String jsonStr, Class<T> cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(jsonStr, cls);
        }
        return t;
    }

    /**
     * 转成list
     *
     * @param jsonStr json 字符串
     * @param type    类型
     * @return
     */
    public static <T> List<T> GsonToList(String jsonStr, Type type) {
        List<T> list = null;
        if (gson != null) {
            list = gson.fromJson(jsonStr, type);
        }
        return list;
    }


    /**
     * 转成map的
     *
     * @param jsonStr json 字符串
     * @return
     */
    public static <T> Map<String, T> GsonToMaps(String jsonStr, Type type) {
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(jsonStr, type);
        }
        return map;
    }

    /**
     * 转成list
     *
     * @param jsonStr json 字符串
     * @param type    类型
     * @return
     */
    public static <T> LinkedHashSet<T> GsonToSet(String jsonStr, Type type) {
        LinkedHashSet<T> list = null;
        if (gson != null) {
            list = gson.fromJson(jsonStr, type);
        }
        return list;
    }
}
